﻿using ChatBackend.Common.Encryption;
using ChatBackend.Common.Enums;
using ChatBackend.DBContext.LoginRepository;
using ChatBackend.Entity.Entities;

namespace ChatBackend.Services.LoginService
{
    public class LoginService : ILoginService
    {
        private readonly ILoginRepository _loginRepo;

        public LoginService(ILoginRepository loginRepository)
        {
            _loginRepo = loginRepository;
        }

        /// <summary>
        /// 注册账号
        /// </summary>
        /// <returns></returns>
        public async Task<bool> RegisteredAccount(string userName, string UID, string PWD, Gender gender)
        {
            //先检测账号是否已存在
            if (await _loginRepo.IsAnyAsync(x => x.UID == UID))
            {
                throw new Exception("账号已存在");
            }

            //密码需要md5加密
            PWD = MD5Helper.GetMD5Hash(PWD);

            UserEntity userEntity = new UserEntity(userName, UID, PWD, gender);
            var result = await _loginRepo.InsertAsync(userEntity);
            return result;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public async Task<bool> Login(string UID, string PWD)
        {
            //分为两步 1检测账号是否存在 2修改用户在线状态

            var user = await _loginRepo.GetSingleAsync(x => x.UID == UID && x.PWD == PWD);
            if (user is not null)
            {
                user.AccountStatus = AccountStatus.Online;
                return await _loginRepo.UpdateAsync(x => user, x => x.Id == user.Id);
            }
            else
            {
                throw new Exception("账号或密码错误！");
            }
        }
    }
}